package edu.suda.LoopCodePlus.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import edu.suda.LoopCodePlus.common.Result;
import edu.suda.LoopCodePlus.entity.User;
import edu.suda.LoopCodePlus.entity.UserExtra;
import edu.suda.LoopCodePlus.service.UserService;
import edu.suda.LoopCodePlus.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtUtil jwtUtil;

    @PostMapping("register")
    public Result register(@RequestBody @Valid User user, BindingResult bindingResult){
        System.out.println("注册参数验证中");
        if (bindingResult.hasErrors()){
            List<ObjectError> allErrors=bindingResult.getAllErrors();
            String errors= "";
            System.out.println(user);
            for (ObjectError allError : allErrors) {
                System.out.printf("验证不通过的消息是%s\n",allError.getDefaultMessage());
                errors+=allError.getDefaultMessage()+"\n";
            }
            return Result.failure("参数验证失败",errors);
        }
        System.out.println("注册参数验证成功");
        System.out.println("当前注册用户为:");
        System.out.println(user);
        System.out.println("将用户存储在数据库中");
        try{
            if (userService.save(user)){
                return Result.success("注册成功",user);
            }
            else {
                System.out.println("用户信息或用户额外信息存储失败");
                return Result.failure("注册失败",user);
            }
        }catch (Exception e){
            if(userService.findUserByRegMail(user.getRegMail())!=null){
                return Result.failure("注册失败,邮箱已被注册");
            }
            return Result.failure("注册失败,数据库未成功保存用户数据",user);
        }
    }
    @PostMapping("login")
    public Result login(@RequestBody Map<String,Object> data){
        System.out.println("收到登录请求");
        String regMail=(String)data.get("regMail");
        String passwd=(String)data.get("passwd");
        System.out.println("邮箱:"+regMail);
        System.out.println("密码:"+passwd);
        System.out.println("输入参数验证");
        if (regMail==null||passwd==null) return Result.failure("邮箱或密码为空");
        System.out.println("输入参数验证成功");
        System.out.println("开始验证用户信息");
        User user=userService.findUserByRegMail(regMail);
        if (user==null) {
            System.out.println("验证失败,用户不存在");
            return Result.failure("邮箱或密码错误");
        }
        String token;
        if (user.getPasswd().equals(passwd)){
            try{
                token=jwtUtil.createToken(user.getUserId().toString());
            }catch (Exception e){
                System.out.println("token生成失败");
                return Result.failure("登录失败,token生成失败");
            }
            System.out.println("token生成,将在48h后过期:"+token);
        }
        else {
            System.out.println("验证失败,密码错误");
            return Result.failure("邮箱或密码错误");
        }
        //验证用户vip是否过期
        UserExtra userExtra=userService.findUserExtraById(user.getUserId());
        if(userExtra.getVipTime()==null){
            System.out.println("用户未开通vip");
        }
        else{
            if(userExtra.getVipTime().before(new java.util.Date())){
                System.out.println("用户vip已过期");
                try{
                    userExtra.setVipTime(null);
                    user.setRole("普通用户");
                    if(userService.updateUserExtraById(user.getUserId(),userExtra)&&userService.updateUserRoleById(user.getUserId(),user)){
                        System.out.println("用户vip已过期,已重置vip时间和用户身份");
                    }
                    else{
                        System.out.println("用户vip已过期,重置vip时间失败");
                        return Result.failure("用户vip已过期,重置vip时间失败");
                    }
                }catch (Exception e){
                    System.out.println("用户vip已过期,重置vip时间失败");
                    return Result.failure("用户vip已过期,重置vip时间失败");
                }
            }
            else{
                System.out.println("用户vip未过期");
            }
        }
        //返回用户信息
        System.out.println("登录成功,返回该用户信息:"+user);
        return Result.success(token,user);
    }

    @GetMapping("/baseInfo")
    public Result baseInfo(HttpServletRequest request, HttpServletResponse response){
        System.out.println("验证token");
        String token = request.getHeader("Authorization");
        Integer userId;
        try {
            DecodedJWT decodedJWT = jwtUtil.verifyToken(token);
            userId = Integer.parseInt(decodedJWT.getClaim("userId").asString());
            System.out.println("数据验证成功，userId:"+userId);
        }catch (Exception e){
            System.out.println("token验证失败");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return Result.failure("token验证失败");
        }
        User user;
        try{
            System.out.println("开始获取用户信息");
            user=userService.findUserById(userId);
            System.out.println("获取用户信息成功"+user);
            return Result.success(user);
        }catch (Exception e){
            System.out.println("获取用户信息失败");
            return Result.failure("获取用户信息失败");
        }
    }

    @GetMapping("/getExtra")
    public Result getExtra(HttpServletRequest request, HttpServletResponse response){
        System.out.println("收到获取用户额外信息请求");
        System.out.println("验证token");
        String token = request.getHeader("Authorization");
        Integer userId;
        try {
            DecodedJWT decodedJWT = jwtUtil.verifyToken(token);
            userId = Integer.parseInt(decodedJWT.getClaim("userId").asString());
            System.out.println("token验证成功，userId:"+userId);
        }catch (Exception e){
            System.out.println("token验证失败");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            return Result.failure("token验证失败");
        }
        try{
            UserExtra userExtra=userService.findUserExtraById(userId);
            if(userExtra==null){
                return Result.failure("用户额外信息为空");
            }
            System.out.println("获取用户额外信息成功"+userExtra);
            return Result.success(userExtra);
        }catch (Exception e){
            System.out.println("获取用户额外信息失败");
            return Result.failure("获取用户额外信息失败");
        }
    }
}
